package com.example.springcloud.controller;

import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.entities.Payment;
import com.example.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-01-28
 * Time: 15:28
 */

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;// 通过它可以得到注册进 eureka 的微服务相关信息

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        // 得到微服务的名称
        /*
            即 yml 里面的：spring:application:name:
         */
        services.forEach(service -> {
            log.info("service:{}", service);
        });

        // 微服务下的全部具体实例，得到这个微服务相关的详细信息
        discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE").forEach(instance -> {
            log.info("instance:{},{},{},{}",
                    instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getUri());
        });

        return discoveryClient;
    }


    @PostMapping("/create")
    public CommonResult crete(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("create result:{}", result);

        if (result > 0) {
            return new CommonResult(200, "插入数据库成功！,serverPort:" + serverPort, result);
        }
        return new CommonResult(500, "插入数据库失败！");
    }

    @GetMapping("/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);

        log.info("getPaymentById:{}", payment);

        if (payment != null) {
            return new CommonResult<>(200, "查询成功！,serverPort:" + serverPort, payment);
        }

        return new CommonResult<>(400, "查询失败！,serverPort:" + serverPort);
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/zipkin")
    public String paymentZipkin() {
        return "This is payment zipkin!";
    }

}
